// pages/movie/movie.js
/**
 * 虚拟化长列表：https://mp.weixin.qq.com/s?__biz=MjM5NTY1MjY0MQ==&mid=2650857776&idx=4&sn=85d53eabb0c7743aaa6b0075bb4ce2f3&chksm=bd01747e8a76fd68aa053ec8cff7bba89512e2b83e5a71425fa4c64c0957502ca179d660266e&scene=27
 */
import { getTopRatedMovies, getMovieOnInfoList, getMoreClassicList } from '../../api/movie'
const createRecycleContext = require('miniprogram-recycle-view')
function rpx2px(rpxNum) {
  return rpxNum * (1 / 750 * wx.getSystemInfoSync().windowWidth)
}
Page({
  ctx: null, // recycle-view的上下文对象
  /**
   * 页面的初始数据
   */
  data: {
    cityName: '定位中...',
    tag: 'online',
    topRatedMovies: [], // 最受好评电影
    onlineMovie: {}, // 正在热映电影对象
    classicList: [], // 经典电影列表
    newList: [], // 经典电影每次新加载的分页数据
    limit: 10,
    page: 1,
    hasMore: true
  },
  toggle(e) {
    const tag = e.target.dataset.tag
    if (tag === 'classics') {
      this.getClassicListData(0)
    }

    this.setData({
      tag
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.getLocation()
    this.getTopRatedMoviesData()
    this.getMovieOnInfoListData()
  },
  // 获取定位城市
  getLocation() {
    wx.getLocation({
      type: 'wgs84',
      success: (res) => {
        var latitude = res.latitude;  // 纬度
        var longitude = res.longitude;  // 经度
        // 使用逆地理编码API接口获取城市信息
        wx.request({
          url: 'https://api.map.baidu.com/reverse_geocoding/v3/',
          data: {
            ak: 'xzvThyo6PqzT6vbb4GiSGv8d2Z8Eqg5M',
            location: latitude + ',' + longitude,
            output: 'json',
            coordtype: 'wgs84ll'
          },
          success: (res) => {
            var cityName = res.data.result.addressComponent.city;  // 城市名称
            this.setData({
              cityName
            })
          },
          fail: function (res) {
            console.log('获取城市信息失败');
          }
        });
      },
      fail: err => {
        console.log('---err---', err)
      }
    })
  },
  // 获取最受欢迎的电影列表
  async getTopRatedMoviesData() {
    const res = await getTopRatedMovies()
    this.setData({
      topRatedMovies: res.movieList
    })
  },
  // 获取正在热映的电影列表
  async getMovieOnInfoListData() {
    const res = await getMovieOnInfoList()
    this.setData({
      onlineMovie: res
    })
  },
  // 获取经典电影列表
  async getClassicListData(offset) {
    const res = await getMoreClassicList({
      sortId: 3,
      showType: 3,
      limit: this.data.limit,
      offset
    })

    /**
    this.setData({
      classicList: [...this.data.classicList, ...res]
    }, () => {
      if (this.data.classicList.length > 100) {
        this.setData({
          hasMore: false
        })
      }
    })
     */

    this.setData({
      newList: res
    }, () => {
      if (this.data.classicList.length > 100) {
        this.setData({
          hasMore: false
        })
      }
    })

    this.data.classicList = this.data.classicList.concat(res)
    // console.log('---classicList---', this.data.classicList)
    this.setRecycleContext()
  },
  setRecycleContext() {
    if (!this.ctx) {
      const args = {
        id: 'recycleId',
        dataKey: 'classicList', // 与recycle-item中wx:for的值保持一致
        page: this,
        useInPage: false,
        height: 300,
        itemSize: {
          // 这个参数也可以直接传下面定义的this.itemSizeFunc函数
          width: rpx2px(750),
          height: rpx2px(196)
        },
        position: {
          height: rpx2px(88)
        }
      }
      this.ctx = createRecycleContext(args)
    }

    this.ctx.append(this.data.newList)
  },
  onReachBottom() {
    if (this.data.tag === 'classics' && this.data.hasMore) {
      this.data.page++
      this.getClassicListData(this.data.page * this.data.limit)
    }
  },
  goToSearch() {
    wx.navigateTo({
      url: '/subpkg/search/search',
    })
  },
  onShow() {
    const token = wx.getStorageSync('token')
    if (!token) {
      wx.setTabBarItem({
        index: 3,
        text: '未登录'
      })
    } else {
      wx.setTabBarItem({
        index: 3,
        text: '我的'
      })
    }
  }
})